package com.zhanghu.backendZray.job;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.zhanghu.backendZray.constants.OilPriceSupportCityConstant;
import com.zhanghu.backendZray.pojo.dto.oilPrice.OilPriceDTO;
import com.zhanghu.backendZray.pojo.entity.OilPrice;
import com.zhanghu.backendZray.service.OilPriceService;
import com.zhanghu.backendZray.utils.oilPrice.OilPriceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @author ZhangDong
 * @date 2025/1/19 16:54
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OilPriceJob {

    private final OilPriceService oilPriceService;

    /**
     * 每天凌晨0点获取油价
     */
    @Scheduled(cron = "8 0 0 * * ?")
    public void getOilPrice() {
        long start = System.currentTimeMillis();
        log.info("定时获取油价job, begin...");
        LocalDate now = LocalDate.now();
        OilPriceSupportCityConstant.AREA_LIST.forEach(area -> {
            try {
                OilPriceDTO oilPriceDTO = OilPriceUtil.getOilPrice(area);
                if (oilPriceDTO != null) {
                    OilPrice oilPrice = new OilPrice();
                    BeanUtil.copyProperties(oilPriceDTO, oilPrice);
                    oilPrice.setArea(oilPriceDTO.getName());
                    oilPrice.setPullDate(now);
                    oilPriceService.save(oilPrice);
                    log.info("定时获取油价job, 插入地区:{}的油价数据成功, 日期:{}", area, JSON.toJSONString(now));
                } else {
                    log.error("定时获取油价job, 插入地区:{}的油价数据失败, 日期:{}", area, JSON.toJSONString(now));
                }
            } catch (Exception e) {
                log.error("定时获取油价job, 插入地区:{}的油价数据失败, 日期:{}, error:{}", area, JSON.toJSONString(now), e.getMessage());
            }
        });
        log.info("定时获取油价job, end... 耗时:{}ms", System.currentTimeMillis() - start);
    }
}
